package com.sy.util;

import com.sun.mail.smtp.SMTPMessage;

import javax.mail.*;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.util.Properties;

public class SMTPMailUtil {

    private static Store store;
    private static Folder folder;

    public static void receive() {
        for(File file:getAllProties()) {
            if (!file.isDirectory()) {
                System.err.println(file.getPath());
                try {
                    // 准备连接服务器的会话信息
                    Properties props = new Properties();
                    InputStream inputStream = new FileInputStream(file.getPath());
                    props.load(inputStream);
                    props.setProperty("mail.store.protocol", "smtp");       // 使用pop3协议
                    props.setProperty("mail.smtp.host", "smtp.qq.com");       // pop3服务器
                    props.setProperty("mail.smtp.port", "465");           // 端口
                    props.setProperty("mail.smtp.ssl.enable", "true");
                    props.setProperty("mail.smtp.timeout", "10000");
                    // 创建Session实例对象
                    Session session = Session.getInstance(props);
                    store = session.getStore("smtp");
                    store.connect("lshoufa@qq.com", "baigapmwvgrqdief");
                    folder = store.getFolder("INBOX");
                    // 以读写模式打开收件箱
                    folder.open(Folder.READ_WRITE);
                    // 获得收件箱的邮件列表
                    Message[] messages = folder.getMessages();

                    // 打印不同状态的邮件数量
                    System.out.println("收件箱中共" + messages.length + "封邮件!");
                    System.out.println("收件箱中共" + folder.getUnreadMessageCount() + "封未读邮件!");
                    System.out.println("收件箱中共" + folder.getNewMessageCount() + "封新邮件!");
                    System.out.println("收件箱中共" + folder.getDeletedMessageCount() + "封已删除邮件!");

                    System.out.println("------------------------开始解析邮件----------------------------------");

                    // 解析邮件
                    for (Message message : messages) {
                        SMTPMessage msg = (SMTPMessage) message;
                        String subject = MimeUtility.decodeText(msg.getSubject());
                        if (!msg.getFlags().contains(Flags.Flag.SEEN)) {
                            System.out.println("[" + subject + "]未读，是否需要阅读此邮件（yes/no）？");
                            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                            String answer = reader.readLine();
                            if ("yes".equalsIgnoreCase(answer)) {
//                POP3ReceiveMailTest.parseMessage(msg);  // 解析邮件
                                // 第二个参数如果设置为true，则将修改反馈给服务器。false则不反馈给服务器
                                msg.setFlag(Flags.Flag.SEEN, true);   //设置已读标志
                            }
                        }
                    }
                } catch (NoSuchProviderException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 关闭资源
     * @throws MessagingException
     */
    public static void close() {
        try {
            folder.close(true);
            store.close();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public static File[] getAllProties() {
        String path = Const.MailPath.smtpPath;
        File[] files = new File(path).listFiles();	//遍历path下的文件和目录，放在File数组中
        return files;
    }
}
